<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px" style="min-height: 100vh; background-color: rgb(22,46,86)">
        <div class="aside-head-info"
             style="width: 200px; height: 80px; align-items: center; justify-items: center; display: flex">
          <span
              style="color: #f9f9f9; display: flex; align-items: center; justify-content: center; width: 200px">欢迎您，系统管理员</span>
        </div>
        <el-menu style="border: none" :default-active="currentUrl" router background-color="#162E56"
                 text-color="#f9f9f9">
          <el-menu-item index="/top-manager/index">
            <template #title>
              <el-icon>
                <User/>
              </el-icon>
              用户首页
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/account-manage">
            <template #title>
              <el-icon>
                <Edit/>
              </el-icon>
              账户管理
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/auth-distribute">
            <template #title>
              <el-icon>
                <Lock/>
              </el-icon>
              权限分配
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/manage-restaurant">
            <template #title>
              <el-icon>
                <DishDot/>
              </el-icon>
              食堂管理
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/remark-control">
            <template #title>
              <el-icon>
                <ChatDotSquare/>
              </el-icon>
              评论管理
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/community-surveillance">
            <template #title>
              <el-icon>
                <Camera/>
              </el-icon>
              社区管理
            </template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header
            style="box-shadow: 2px 0 6px rgba(0, 21, 41, .36); display: flex; align-items: center; justify-content: space-between">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="item in route.matched" :to="{path: item.path}">{{ item.meta.title }}
            </el-breadcrumb-item>

          </el-breadcrumb>
          <div class="avatar-container" style="align-items: center; display: flex; justify-content: flex-end">
            <el-dropdown style="display: flex; align-items: center; justify-content: flex-end" placement="bottom">
        <span class="el-dropdown-link"
              style="display: flex; align-items: center;">
          <el-avatar :size="24" :src="avatarSrc" style="margin: 0 5px"/>
          {{ '欢迎您，' + nickname }}
        </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>个人中心</el-dropdown-item>
                  <el-dropdown-item>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main>
          <el-form :model="formRef" ref="queryFormRef" :inline="true">
            <el-form-item label="管理员用户名">
              <el-input placeholder="请输入管理员用户名" v-model="queryForm.userName"/>
            </el-form-item>
            <el-form-item label="管理员昵称">
              <el-input placeholder="请输入管理员昵称" v-model="queryForm.nickName"/>
            </el-form-item>
            <el-form-item>
              <el-button @click="handleQuery" :icon="Search" size="small">搜索</el-button>
              <el-button @click="resetQuery" :icon="Refresh" size="small">重置</el-button>
            </el-form-item>
          </el-form>
<!--          <el-row>-->
<!--            <el-col :span="3">-->
<!--              <el-button @click="handleAuthDistribute" :icon="Check" >分配权限</el-button>-->
<!--            </el-col>-->
<!--            <el-col :span="3">-->
<!--              <el-button @click="handleUpdateDistribute" :icon="Refresh">重新授权</el-button>-->
<!--            </el-col>-->
<!--            <el-col :span="3">-->
<!--              <el-button @click="handleResetDistribute" :icon="Refresh">取消授权</el-button>-->
<!--            </el-col>-->
<!--          </el-row>-->
          <el-table :data="tableData" v-loading="tableLoading">
            <el-table-column prop="userId" v-if="false" align="center" />
            <el-table-column prop="userName" label="用户名" align="center"/>
            <el-table-column prop="nickName" label="昵称" align="center"/>
            <el-table-column label="头像" align="center">
              <template #default="scope">
                <img :src="scope.row.avatar" style="width: 50px; height: 50px" alt="暂无用户头像"/>
              </template>
            </el-table-column>
            <el-table-column prop="phonenumber" label="手机" align="center"/>
            <el-table-column prop="restId" v-if="false"/>
            <el-table-column prop="restName" label="管理食堂名称" align="center"/>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button link :icon="Unlock" @click="handleAuthDistribute(scope.row)">分配权限</el-button>
                <el-button link :icon="Refresh" @click="handleUpdateDistribute(scope.row)">重新授权</el-button>
                <el-button link :icon="Lock" @click="handleResetDistribute(scope.row)">取消授权</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog :title="dialogTitle" v-model="dialogVis" append-to-body width="400px">
            <el-form :model="form" ref="formRef" :rules="formRule">
              <el-form-item label="请选择管理的食堂" prop="restId">
                <el-select v-model="form.restId">
                  <el-option v-for="item in restaurantOptions"
                             :label="item.restaurantName"
                             :value="item.restaurantId"
                             :key="item.restaurantId"/>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="handleSubmit(formRef)" type="primary" size="small">确定</el-button>
                <el-button @click="resetSubmit" type="danger" size="small">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {useRoute} from "vue-router";
import {ArrowRight, Refresh, Search, Lock, Unlock} from "@element-plus/icons-vue";
import {queryRestaurantManagerLeadRestaurant, queryRestaurantInfo, addAuth, deleteAuth, updateAuth} from "../../web-api/system-manager/auth-distribute"
import {baseStaticRecourseAPI, NOW_ENVIRONMENT} from "../../baseAPIConfig.js";
import {onBeforeMount} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {generalValidatorJudgeIfEmpty} from "../../utils/common.js";
import {getLocalStorage, KEY_AVATAR, KEY_NICKNAME} from "../../utils/localStorge.js";

const handleQuery = ()=>{
  queryForm.pageNum = 1;
  getList(queryForm);
}

const resetQuery = ()=>{
  resetQueryForm();
  getList(queryForm);
}

// 对话框
let dialogVis = ref(false)
let dialogTitle = ref()

// 表格遮罩层
let tableLoading = ref(false)

// 查询表单
let queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: null,
  // 01表示管理员，本页面所有userType都是01
  userType: "01",
  nickName: null
})

// 查询表单引用
let queryFormRef = ref()

// 重置查询表单
const resetQueryForm = ()=>{
  if(!queryFormRef.value){
    return;
  }
  queryFormRef.value.resetFields();
  queryForm.userType = "01";
  queryForm.pageNum = 1;
  queryForm.pageSize = 10
}

// 为没分配食堂的管理员分配食堂
const handleAuthDistribute = (row)=>{
  if(row.restId==="未分配食堂"){
    form.type = "0"
    form.userId = row.userId;
    dialogVis.value = true
    dialogTitle.value = "分配权限"
  }else{
    ElMessage.error(`${row.userName}已分配为${row.restName}的管理员！`)
  }
}

// 修改已经分配的管理员的管理信息
const handleUpdateDistribute = (row)=>{
  if(row.restId==="未分配食堂"){
    ElMessage.error(`${row.userName}尚未分配管理员！`)
  }else{
    form.type = "1"
    form.userId = row.userId;
    dialogVis.value = true
    dialogTitle.value = "更新权限"
  }
}

// 自定义表单验证规则
let formRule = ref({
  restId: [{validator: generalValidatorJudgeIfEmpty("分配的食堂不能为空！"), trigger: "blur"}]
})

const handleSubmit = (ref)=>{
    ref.validate(valid=>{
      if(valid){
        if(form.type=="0"){
          addAuth({restId: form.restId, userId: form.userId}).then(res=>{
            ElMessage.success("分配权限成功！")
            dialogVis.value= false;
            resetForm();
            getList(queryForm);
          }).catch(err=>{console.log(err)})
        }else{
          updateAuth({restId: form.restId, userId: form.userId}).then(res=>{
            ElMessage.success("更改权限成功！")
            dialogVis.value = false;
            resetForm();
            getList(queryForm);
          })
        }
      }
    })
}

const resetSubmit = ()=>{
  dialogVis.value = false;
  resetForm();
}

// 删除对管理员的授权
const handleResetDistribute = (row)=>{
  ElMessageBox.confirm(`确定要取消对管理员${row.nickName}的授权吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(()=>{
    if(row.restId=="未分配食堂"){
      ElMessage.warning("该用户尚未分配食堂！")
    }else{
      deleteAuth({restId: row.restId, userId: row.userId}).then(res=>{
        ElMessage.success("取消授权成功！")
        getList(queryForm)
      }).catch(err=>{
        console.log(err)
      })
    }
  }).catch(()=>{
    console.log("取消取消授权")
  })
}

let form = reactive({
  userId: null,
  restId: null,
  // 0表示新增，1表示修改
  type: null
})

let formRef = ref()

const resetForm = ()=>{
  if(!formRef.value){
    return;
  }
  formRef.value.resetFields();
}

//
let tableData = ref([])


//
const getList = (query)=>{
  tableLoading.value = true
  queryRestaurantManagerLeadRestaurant(query).then(res=>{
    let temp = [];
    res.rows.map(item=>{
      temp.push({
        userId: item.userId,
        userName: item.userName,
        nickName: item.nickName,
        phonenumber: item.phonenumber,
        avatar: baseStaticRecourseAPI[NOW_ENVIRONMENT]+item.avatar,
        restId: item.restaurant?item.restaurant.restaurantId:"未分配食堂",
        restName: item.restaurant?item.restaurant.restaurantName:"未分配食堂"
      })
    })
    tableData.value = temp;
    tableLoading.value = false
  }).catch(err=>console.log(err))
}

// 食堂选项
let restaurantOptions = ref([])

// 请求食堂数据
const getRestaurantList = ()=>{
  queryRestaurantInfo({}).then(res=>{
    restaurantOptions.value = res.data;
  })
}

let route = useRoute();

// 记录当前路由
let currentUrl = ref()

// 记录当前登录用户昵称
let nickname = ref(getLocalStorage(KEY_NICKNAME))

// 记录当前用户登陆的食堂id
// let restaurantId = getLocalStorage(KEY_RESTAURANT_ID);

// 记录当前登录用户头像，后期应该要大改
let avatarSrc = baseStaticRecourseAPI[NOW_ENVIRONMENT] + getLocalStorage(KEY_AVATAR)

onBeforeMount(()=>{
  getList(queryForm);
  getRestaurantList();
})

onMounted(() => {
  currentUrl.value = route.path;
  console.log(currentUrl);
  console.log(route)
})
</script>

<style scoped>
.is-active {
  color: #f9f9f9 !important;
  background-color: #47739a;
  border-radius: 20px;
  margin: 0 10px;
}

.el-menu-item {
  margin: 5px 10px !important;
}

.el-menu-item:hover {
  border-radius: 20px;
}
</style>